package com.share.tool.generator.api.fm;

import com.share.common.constant.DirConstant;
import com.share.common.utils.JsonUtil;
import com.share.tool.generator.api.config.BaseInfo;
import com.share.tool.generator.api.model.CtrlInfo;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 01401061 - 孙艳强
 * @date 2020/11/21 13:14
 */
public class FmHtmlFormat {
    public static String convert(BaseInfo baseInfo, List<CtrlInfo> result) {

        final String template = "api.ftl";
        final String outFileName = DirConstant.TMP_DIR+File.separator + template + ".html";
        final String templateLoadingPath = new File(ClassLoader.class.getResource("/template/ftl").getPath()).getPath();

        //输出文件定义
        File outFile = new File(outFileName);

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
        cfg.setClassicCompatible(true);/*跳过空值*/
        try {
            Map root = new HashMap();
            /*传json不出问题,如果是java对象，可能会有问题*/
            root.put("baseInfo", JsonUtil.toJsonObj(baseInfo));
            root.put("result", JsonUtil.toJsonArr(result));

            cfg.setDirectoryForTemplateLoading(new File(templateLoadingPath));

            Template temp = cfg.getTemplate(template);
            BufferedWriter bw = new BufferedWriter(new FileWriter(outFile));
            temp.process(root, bw);
            bw.flush();
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return outFile.getAbsolutePath();
    }
}
